package me.jessyan.mvparms.demo.mvp.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.DefaultAdapter;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.platform.ai.control.R;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.OnClick;
import me.jessyan.mvparms.demo.di.component.DaggerUserComponent;
import me.jessyan.mvparms.demo.di.module.UserModule;
import me.jessyan.mvparms.demo.mvp.contract.UserContract;
import me.jessyan.mvparms.demo.mvp.model.entity.User;
import me.jessyan.mvparms.demo.mvp.model.logic.AllDialogUtil;
import me.jessyan.mvparms.demo.mvp.model.logic.TextUtil;
import me.jessyan.mvparms.demo.mvp.presenter.UserPresenter;
import me.jessyan.mvparms.demo.mvp.ui.adapter.ScanResultAdapter;
import me.jessyan.mvparms.demo.util.Utils;

import static com.jess.arms.utils.Preconditions.checkNotNull;

// 注册界面
public class WIFIConfigActivity extends BaseActivity<UserPresenter> implements UserContract.View{

    @BindView(R.id.tv_title)
    TextView mTitle;
    @BindView(R.id.et_wifi_name)
    EditText mWiFiName;
    @BindView(R.id.et_wifi_pwd)
    EditText mWiFiPwd;
    private Context mContext;
    private WifiManager mWifiManager;
    private static final int WIFICIPHER_NOPASS = 0;
    private static final int WIFICIPHER_WEP = 1;
    private static final int WIFICIPHER_WPA = 2;
    @Override
    public void setupActivityComponent(AppComponent appComponent) {
        DaggerUserComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .userModule(new UserModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(Bundle savedInstanceState) {
        return R.layout.activity_wifi_config; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @SuppressLint("WifiManagerLeak")
    @Override
    public void initData(Bundle savedInstanceState) {
        mTitle.setText("WIFI配网");
        mWifiManager = (WifiManager)getSystemService(WIFI_SERVICE);
        String ssid = getIntent().getStringExtra("ssid");
        mWiFiName.setText(ssid);

    }



    private void configChildViews() {


    }

    @Override
    public void showLoading() {

    }



    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        //checkNotNull(message);
        //ArmsUtils.snackbarText(message);
        if (!message.isEmpty()) {

        }
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        killMyself();
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        killMyself();
    }

    @Override
    public void setAdapter(DefaultAdapter adapter) {

    }

    @Override
    public void loginReturn(User user) {

    }

    @Override
    public void logout() {

    }

    @Override
    public void uploadResult(String string) {

    }

    @OnClick(R.id.iv_back)
    public void onBack(View v){
        super.onBackPressed();
    }

    @OnClick(R.id.tv_cancel)
    public void cancel(View v){
        super.onBackPressed();
    }

    @OnClick(R.id.tv_confirm)
    public void confirm(View v){
        configWiFi();
    }


    private void configWiFi(){
        mWifiManager.setWifiEnabled(true);
        WifiConfiguration config = createWifiConfig(mWiFiName.getText().toString(),mWiFiPwd.getText().toString(),WIFICIPHER_WPA);
        int res = mWifiManager.addNetwork(config);
        if(res != -1){
            Toast.makeText(this,"WIFI配置成功",Toast.LENGTH_SHORT).show();
            mWifiManager.enableNetwork(res,true);
            mWifiManager.saveConfiguration();
        }else{
            Toast.makeText(this,"账号/密码错误,或WIFI已连接",Toast.LENGTH_SHORT).show();
        }
    }

    private WifiConfiguration createWifiConfig(String ssid, String password, int type) {
        WifiConfiguration config = new WifiConfiguration();
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        config.SSID = "\"" + ssid + "\"";

        WifiConfiguration tempConfig = isExist(ssid);
        if(tempConfig != null) {
            mWifiManager.removeNetwork(tempConfig.networkId);
        }

        if(type == WIFICIPHER_NOPASS) {
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        } else if(type == WIFICIPHER_WEP) {
            config.hiddenSSID = true;
            config.wepKeys[0]= "\""+password+"\"";
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        } else if(type == WIFICIPHER_WPA) {
            config.preSharedKey = "\""+password+"\"";
            config.hiddenSSID = true;
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            config.status = WifiConfiguration.Status.ENABLED;
        }

        return config;
    }

    private WifiConfiguration isExist(String ssid) {
        List<WifiConfiguration> configs = mWifiManager.getConfiguredNetworks();

        for (WifiConfiguration config : configs) {
            if (config.SSID.equals("\""+ssid+"\"")) {
                return config;
            }
        }
        return null;
    }

}
